package cn.tedu.charging.order.config;

import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * EMQX 配置
 */
@Slf4j
@Configuration
public class MqttConfiguration {
    @Autowired
    private MqttContext mqttContext;
    private String host = "tcp://127.0.0.1:1883";
    private String clientId = "order_service" + Math.random();
    private String userName = "admin";
    private String password = "public";

    @Bean
    public MqttClient mqttClient() throws Exception {
        MqttClient mqttClient = new MqttClient(host, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(userName);
        //密码需要 字符数组 char[] toCharArray 是字符串的一个方法可以把字符串转换为char[]
        options.setPassword(password.toCharArray());
        //清理会话
        options.setCleanSession(true);
        //自动重连
        options.setAutomaticReconnect(true);
        //设置版本号
        options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        MqttConsumer mqttConsumer = new MqttConsumer(mqttClient,mqttContext);
        mqttClient.setCallback(mqttConsumer);
        //通过连接的配置和EMQX进行连接
        mqttClient.connect(options);
        log.debug("MQTT客户端正在连接EMQX");
        return mqttClient;
    }

}
